package com.cheegu.common.parser.gpsdata.util;

import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;

/**
 * @author tac
 * @since 23/03/2018
 */
public abstract class BitUtils {
    public static final int INT_LENGTH = 4;
    public static final int BYTE_BITS = 8;
    public static final int FLOAT_LENGTH = 4;
    public static final int DOUBLE_LENGTH = 8;

    public static byte[] int2bytes(int i) {
        ByteBuffer bb = ByteBuffer.allocate(INT_LENGTH);
        byte[] ret = new byte[INT_LENGTH];
        IntBuffer ib = bb.asIntBuffer();
        ib.put(i);
        bb.get(ret);
        return ret;
    }

    public static long bytes2long(byte[] bytes) {
        long l = 0;
        for (int i = 0; i < bytes.length; i++) {
            if (i >= 8) {
                //越界
                break;
            }
            l |= (((long) bytes[i] & 0xff) << i * BYTE_BITS);
        }
        return l;
    }

    public static byte[] float2bytes(float f) {
        ByteBuffer bb = ByteBuffer.allocate(FLOAT_LENGTH);
        byte[] ret = new byte[FLOAT_LENGTH];
        FloatBuffer fb = bb.asFloatBuffer();
        fb.put(f);
        bb.get(ret);
        return ret;
    }

    public static byte[] double2bytes(double d) {
        ByteBuffer bb = ByteBuffer.allocate(DOUBLE_LENGTH);
        byte[] ret = new byte[DOUBLE_LENGTH];
        DoubleBuffer db = bb.asDoubleBuffer();
        db.put(d);
        bb.get(ret);
        return ret;
    }
}
